package cn.xm.user.controller;

import cn.xm.basic.dto.LogininfoDto;
import cn.xm.basic.dto.PhoneDto;
import cn.xm.basic.result.AjaxResult;
import cn.xm.basic.result.PageList;
import cn.xm.user.domain.Logininfo;
import cn.xm.user.service.UserService;
import cn.xm.user.domain.User;
import cn.xm.user.query.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public UserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        if( user.getId()!=null){
            userService.update(user);
        } else {
                userService.add(user);
        }
        return AjaxResult.me();
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        userService.delete(id);
        return AjaxResult.me();
    }
	
    //获取用户
    @GetMapping("/{id}")
    public User get(@PathVariable("id")Long id)
    {
        return userService.findById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<User> list(){
        return userService.findAll();
    }

    @PostMapping("/phone_register")
    public AjaxResult phoneRegister(@RequestBody PhoneDto phoneDto){
        userService.phoneRegister(phoneDto);
        return AjaxResult.me();
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid LogininfoDto logininfoDto){
        Map<String, Object> map = userService.login(logininfoDto);
        return AjaxResult.me().setResultObj(map);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<User> json(@RequestBody @Valid UserQuery query)
    {
        return userService.queryByPage(query);
    }
}
